<template>
  <div class="usage-analysis">
    <!-- 时间范围选择 -->
    <el-card class="time-range-card">
      <template #header>
        <div class="card-header">
          <span>分析时间范围</span>
          <el-select v-model="timeRange" @change="loadData" style="width: 120px;">
            <el-option label="最近7天" value="7d" />
            <el-option label="最近30天" value="30d" />
            <el-option label="最近90天" value="90d" />
            <el-option label="最近一年" value="365d" />
          </el-select>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ analysisData.summary?.totalClothing || 0 }}</div>
            <div class="stat-label">总衣服数量</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ analysisData.summary?.wornClothing || 0 }}</div>
            <div class="stat-label">已穿衣服</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ analysisData.summary?.unwornClothing || 0 }}</div>
            <div class="stat-label">未穿衣服</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ analysisData.summary?.averageWearFrequency || 0 }}</div>
            <div class="stat-label">平均穿着频率</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 最常穿的衣服 -->
    <el-card class="most-worn-card" v-loading="loading">
      <template #header>
        <span>最常穿的衣服 (Top 10)</span>
      </template>

      <div class="clothing-list">
        <div 
          v-for="item in analysisData.mostWorn" 
          :key="item.clothing.id"
          class="clothing-item"
        >
          <div class="clothing-info">
            <img 
              :src="item.clothing.main_image || '/placeholder-clothing.png'" 
              :alt="item.clothing.name"
              class="clothing-image"
            />
            <div class="clothing-details">
              <h4>{{ item.clothing.name }}</h4>
              <p>{{ item.clothing.category }}</p>
            </div>
          </div>
          
          <div class="usage-stats">
            <div class="wear-count">
              <span class="count">{{ item.wearCount }}</span>
              <span class="label">次</span>
            </div>
            <div class="frequency">
              <span class="freq">{{ item.frequency }}</span>
              <span class="label">次/月</span>
            </div>
            <div class="last-worn">
              <span class="date">{{ formatDate(item.lastWorn) }}</span>
            </div>
          </div>
          
          <div class="usage-bar">
            <el-progress 
              :percentage="getUsagePercentage(item.wearCount)" 
              :show-text="false"
              :stroke-width="6"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 很少穿的衣服 -->
    <el-card class="least-worn-card" v-loading="loading">
      <template #header>
        <span>很少穿的衣服</span>
      </template>

      <div class="clothing-grid">
        <div 
          v-for="item in analysisData.leastWorn" 
          :key="item.clothing.id"
          class="clothing-card"
        >
          <img 
            :src="item.clothing.main_image || '/placeholder-clothing.png'" 
            :alt="item.clothing.name"
            class="card-image"
          />
          <div class="card-content">
            <h5>{{ item.clothing.name }}</h5>
            <p>{{ item.clothing.category }}</p>
            <div class="wear-info">
              <el-tag size="small" type="warning">
                {{ item.wearCount }} 次
              </el-tag>
              <span class="last-worn-text">
                {{ item.lastWorn ? formatDate(item.lastWorn) : '从未穿过' }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 从未穿过的衣服 -->
    <el-card class="unworn-card" v-loading="loading" v-if="analysisData.unworn?.length > 0">
      <template #header>
        <div class="card-header">
          <span>从未穿过的衣服</span>
          <el-tag type="danger">{{ analysisData.unworn?.length || 0 }} 件</el-tag>
        </div>
      </template>

      <div class="clothing-grid">
        <div 
          v-for="item in analysisData.unworn" 
          :key="item.clothing.id"
          class="clothing-card unworn"
        >
          <img 
            :src="item.clothing.main_image || '/placeholder-clothing.png'" 
            :alt="item.clothing.name"
            class="card-image"
          />
          <div class="card-content">
            <h5>{{ item.clothing.name }}</h5>
            <p>{{ item.clothing.category }}</p>
            <el-tag size="small" type="info">从未穿过</el-tag>
          </div>
          <div class="card-actions">
            <el-button size="small" type="primary" @click="createOutfitWithItem(item.clothing)">
              创建搭配
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 使用建议 -->
    <el-card class="suggestions-card">
      <template #header>
        <span>使用建议</span>
      </template>

      <div class="suggestions">
        <el-alert
          v-if="analysisData.summary?.unwornClothing > 5"
          title="衣柜利用率偏低"
          :description="`您有 ${analysisData.summary.unwornClothing} 件衣服从未穿过，建议尝试新的搭配组合。`"
          type="warning"
          :closable="false"
          style="margin-bottom: 16px;"
        />
        
        <el-alert
          v-if="analysisData.mostWorn?.length > 0 && analysisData.mostWorn[0].wearCount > 10"
          title="过度依赖某些单品"
          :description="`您经常穿 ${analysisData.mostWorn[0].clothing.name}，建议尝试其他类似单品增加搭配多样性。`"
          type="info"
          :closable="false"
          style="margin-bottom: 16px;"
        />
        
        <div class="suggestion-tips">
          <h4>优化建议：</h4>
          <ul>
            <li>尝试将很少穿的衣服与常穿的单品搭配</li>
            <li>定期整理衣柜，考虑捐赠或处理从未穿过的衣服</li>
            <li>记录穿搭心得，了解自己的偏好变化</li>
            <li>设置提醒，定期尝试新的搭配组合</li>
          </ul>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { analysisAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const timeRange = ref('30d')
const analysisData = reactive({
  summary: {},
  mostWorn: [],
  leastWorn: [],
  unworn: []
})

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const response = await analysisAPI.getClothingUsage({ timeRange: timeRange.value })
    
    if (response.code === 200) {
      Object.assign(analysisData, response.data)
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取使用频率分析失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 计算使用百分比
const getUsagePercentage = (wearCount) => {
  const maxCount = analysisData.mostWorn[0]?.wearCount || 1
  return Math.round((wearCount / maxCount) * 100)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '从未'
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays}天前`
  if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`
  if (diffDays < 365) return `${Math.floor(diffDays / 30)}个月前`
  return `${Math.floor(diffDays / 365)}年前`
}

// 为单品创建搭配
const createOutfitWithItem = (clothing) => {
  // 这里应该跳转到创建搭配页面，并预选该单品
  ElMessage.info('跳转到创建搭配页面')
}

// 页面初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.usage-analysis {
  space-y: 20px;
}

.time-range-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item {
  text-align: center;
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.most-worn-card,
.least-worn-card,
.unworn-card,
.suggestions-card {
  margin-bottom: 20px;
}

.clothing-list {
  space-y: 16px;
}

.clothing-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 12px;
}

.clothing-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.clothing-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 16px;
}

.clothing-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.clothing-details p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.usage-stats {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 20px;
  min-width: 80px;
}

.wear-count,
.frequency {
  text-align: center;
  margin-bottom: 4px;
}

.count,
.freq {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.label {
  font-size: 12px;
  color: #666;
  margin-left: 2px;
}

.last-worn .date {
  font-size: 12px;
  color: #999;
}

.usage-bar {
  width: 100px;
}

.clothing-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.clothing-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.clothing-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.clothing-card.unworn {
  border-color: #f56c6c;
  background: #fef0f0;
}

.card-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.card-content {
  padding: 12px;
}

.card-content h5 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #333;
}

.card-content p {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
}

.wear-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-worn-text {
  font-size: 11px;
  color: #999;
}

.card-actions {
  padding: 8px 12px;
  border-top: 1px solid #eee;
  background: #fafafa;
}

.suggestions {
  space-y: 16px;
}

.suggestion-tips h4 {
  margin: 16px 0 8px 0;
  color: #333;
}

.suggestion-tips ul {
  margin: 0;
  padding-left: 20px;
}

.suggestion-tips li {
  margin-bottom: 8px;
  color: #666;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .clothing-item {
    flex-direction: column;
    text-align: center;
  }
  
  .clothing-info {
    flex-direction: column;
    margin-bottom: 12px;
  }
  
  .clothing-image {
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .usage-stats {
    flex-direction: row;
    justify-content: space-around;
    width: 100%;
    margin: 12px 0;
  }
  
  .usage-bar {
    width: 100%;
  }
  
  .clothing-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>
